// service/UserService.java
package service.User;

import backend.GeneralDatabase;
import backend.DiseaseItem;
import backend.EmptyOutput;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class UserService {
    private final GeneralDatabase database;
    private final Map<String, DiseaseItem[]> diseaseData = new HashMap<>();

    public UserService(GeneralDatabase database) {
        this.database = database;
    }

    public String[] getAllDepartments() throws EmptyOutput {
        return database.getAllDepartments();
    }

    public QueryResult<DiseaseItem[]> queryDiseasesByDepartment(String departmentName) {
        try {
            DiseaseItem[] result = database.queryDepartments(departmentName);
            diseaseData.put(departmentName, result);
            return QueryResult.success(result);
        } catch (EmptyOutput e) {
            return QueryResult.error("科室数据为空");
        } catch (Exception e) {
            return QueryResult.error("系统错误: " + e.getMessage());
        }
    }

    public QueryResult<DiseaseItem[]> performSearch(String keyword) {
        try {
            DiseaseItem[] diseases = database.queryDiseases(keyword);
            if (diseases == null || diseases.length == 0) {
                diseases = database.querySymptoms(keyword);
            }
            return QueryResult.success(diseases);
        } catch (EmptyOutput e) {
            return QueryResult.error("未找到相关疾病信息");
        } catch (Exception e) {
            return QueryResult.error("搜索错误: " + e.getMessage());
        }
    }

    public DiseaseItem[] getCachedDiseases(String departmentName) {
        return diseaseData.getOrDefault(departmentName, new DiseaseItem[0]);
    }
}
